package avicit.bdp.dds;

import avicit.platform6.core.rest.msg.ResponseMsg;
import com.alibaba.fastjson2.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Base64;
import java.util.Map;
import java.util.Properties;

import static org.junit.Assert.assertEquals;

public class TestUtils {

    public static String token;

    public static String PT6_URL;
    public static String PT6_USERNAME;
    public static String PT6_PASSWORD;
    /** 测试环境配置信息 */
    public static String HOSTPORT;
    public static String DMS_HOSTPORT;

    public static final String username = "avicit2015";
    public static final String password = "avicit2015";

    @BeforeClass
    public static void init() throws Exception{
        Properties resource = new Properties();
        InputStream in;
        System.out.println("ready to load properties......");
        String propertyPath = System.getProperty("test.file.path");
        if (propertyPath == null || "".equals(propertyPath)) {
            propertyPath = "unittest.properties";
            // 使用ClassLoader加载properties配置文件生成对应的输入流
            in = TestUtils.class.getClassLoader().getResourceAsStream(propertyPath);
            System.out.println("can not find vm option[test.file.path], use default properties");
        } else {
            // 使用FileInputStream加载properties配置文件生成对应的输入流
            in = new FileInputStream(propertyPath);
            System.out.println("read properties from vm option[test.file.path], path is: " +propertyPath);
        }

        // 使用properties对象加载输入流
        resource.load(in);

        PT6_URL = resource.getProperty("test.pt6.address");
        PT6_USERNAME = resource.getProperty("test.pt6.username");
        PT6_PASSWORD = resource.getProperty("test.pt6.password");

        HOSTPORT = resource.getProperty("test.dds.address");
        DMS_HOSTPORT = resource.getProperty("test.dms.address");

        System.out.println("end load properties......");

        token = getToken();
    }

    /**
     * 单个测试用例运行前准备工作
     */
    @Before
    public void setUp() {

    }

    /**
     * 单个测试用例运行后销毁工作
     */
    @After
    public void tearDown() {

    }

    /**
     * 所有用例执行完成后准备工作
     */
    @AfterClass
    public static void destroy() {

    }

    @Test
    public void testReadProperties() {
        System.out.println("HOST_PORT = " + HOSTPORT);
        Assert.assertNotNull(HOSTPORT);
    }

    private static final RestTemplate restTemplate = new RestTemplate();

    public static void createFile(String fileName) {
        try{
            File file = new File(System.getProperty("user.dir") + "/" + fileName);
            if(!file.exists()){
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file.getName(), true);
            fileWriter.write("name,age,work");
            fileWriter.close();
            System.out.println("文件创建成功！");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteFile(String fileName) {
        try{
            File file = new File(System.getProperty("user.dir") + "/" + fileName);
            file.delete();
            System.out.println("删除文件成功！");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HttpEntity<MultiValueMap<String, Object>> buildUploadFileHttpEntity(MultiValueMap<String, Object> form) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("multipart/form-data"));
        headers.add("X-Access-Token", token);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        return httpEntity;
    }

    public static HttpEntity<String> buildPostHttpEntity(String param) {
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("X-Access-Token", token);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    public static HttpEntity<String> buildDeleteHttpEntity(String param) {
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("X-Access-Token", token);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * Get方法需要的HttpEntity
     */
    public static HttpEntity<String> buildGetHttpEntity() {
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("X-Access-Token", token);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        return new HttpEntity<String>(null, headers);
    }

    public static void handleFailedRequest(ResponseEntity<ResponseMsg> result) {
        if (result != null && result.getBody() != null) {
            String retCode = result.getBody().getRetCode();
            if ("500".equals(retCode)) {
                System.out.println("=============================");
                System.out.println("==========请求失败============");
                System.out.println(result.getBody().getErrorDesc());
                System.out.println("=============================");
            }
        } else {
            System.out.println("请求失败，未获取到请求返回体");
        }
    }

    public static String getToken() {
        ResponseEntity<ResponseMsg> result = restTemplate.postForEntity(TestUtils.PT6_URL, TestUtils.buildLoginParam(), ResponseMsg.class);
        TestUtils.handleFailedRequest(result);
        assertEquals("200", result.getBody().getRetCode());
        // 获取token
        ResponseMsg responseMsg = result.getBody();
        Map<String, String> responseBody = (Map<String, String>) responseMsg.getResponseBody();
        String token = responseBody.get("token");

        return token;
    }

    public static HttpEntity<String> buildLoginParam() {
        JSONObject param = new JSONObject();
        param.put("autoLogin", true);
        param.put("username", PT6_USERNAME);
        param.put("password", PT6_PASSWORD);

        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        return new HttpEntity<>(param.toJSONString(), headers);
    }

    public static void main(String[] args) {

    }

}
